package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @ClassName: douyin
 * @Author: djun
 * @Date: create in 2021/9/22 17:35
 * @Description:
 */
@RequestMapping("/api")
@RestController
public class douyin {

    public static String DOU_YIN_BASE_URL = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=";
    /**
     * @param url
     * @author djun
     * @description 解析抖音无水印视频
     * @date 2021/9/22 21:05
     */
    @PostMapping("/parseVideoUrl")
    @ResponseBody
    public String parseVideoUrl(@RequestBody String url) throws Exception {
        try{
            // 获取短连接码
            String sub = "https://v.douyin.com/"+url.split("https://v.douyin.com/")[1].substring(0, 7);
            // 通过短连接获取长链接
            String redirectUrl = Jsoup.connect(sub).followRedirects(true).execute().url().toString();
            // 获取itemId
            String itemId = redirectUrl.split("https://www.douyin.com/video/")[1].replaceAll("[^\\d]", "");
            // 重新信息页面
            String newUrl = DOU_YIN_BASE_URL+itemId;
            // 获取主页面，核心数据
            String body = Jsoup.connect(newUrl).ignoreContentType(true).execute().body();
            // 获取列表
            String item_list = String.valueOf(JsonToMapUtil.toMap(body).get("item_list")).toString();
            String substring = item_list.substring(1, item_list.length() - 1);
            String video = String.valueOf(JsonToMapUtil.toMap(substring).get("video"));
            String play_addr = String.valueOf(JsonToMapUtil.toMap(video).get("play_addr"));
            String url_list = String.valueOf(JsonToMapUtil.toMap(play_addr).get("url_list"));
            String play_url = url_list.substring(2, url_list.length() - 2);
            play_url = play_url.split("playwm")[0]+"play"+play_url.split("playwm")[1];
            return play_url;
        }catch (Exception e){
            return  null;
        }
    }


}
class JsonToMapUtil {

    /**
     * 依据json字符串返回Map对象
     *
     * @param json
     * @return
     */
    public static Map<String, Object> toMap(String json) {
        Map<String,Object> map = JSON.parseObject(json,Map.class);
        return map;
    }

    /**
     * 递归解析JSONObject转换成map
     * 存在的问题：如果json数据中存在一样的key，则后面的值会覆盖前面的key
     * @param jsonObject
     * @return
     */
    public static Map<String,Object> analysis(JSONObject jsonObject){
        Map<String,Object> result = new HashMap<>();
        Set<String> keys = jsonObject.keySet();
        keys.parallelStream().forEach(key->{
            Object value = jsonObject.get(key);
            if(value instanceof JSONObject){
                JSONObject valueJsonObject= (JSONObject) value;
                result.putAll(analysis(valueJsonObject));
            }else if(value instanceof JSONArray){
                JSONArray jsonArray = (JSONArray) value;
                if(jsonArray.size() == 0){
                    return;
                }
                analysisJSONArray(jsonArray,result);
            }else{
                result.put(key,value);
            }
        });
        return result;
    }

    /**
     * 递归解析JSONArray
     * @param jsonArray
     * @param map
     */
    public static void analysisJSONArray(JSONArray jsonArray, Map<String,Object> map){
        jsonArray.parallelStream().forEach(json->{
            if(json instanceof JSONObject){
                JSONObject valueJsonObject= (JSONObject) json;
                map.putAll(analysis(valueJsonObject));
            }else if(json instanceof JSONArray){
                JSONArray tmpJsonArray = (JSONArray) json;
                if(tmpJsonArray.size() == 0){
                    return;
                }
                analysisJSONArray(tmpJsonArray,map);
            }

        });
    }
}
